<template>
  <div class="course-hours-overview">
    <div class="page-header">
      <h1 class="page-title">教学课时总览</h1>
      <p class="page-subtitle">查看和管理所有教学课时信息</p>
    </div>

    <!-- 统计概览 -->
    <el-row :gutter="20" style="margin-bottom: 24px;">
      <el-col :span="6">
        <el-card>
          <div class="stat-item">
            <div class="stat-value">{{ totalStandardHours }}</div>
            <div class="stat-label">{{ filterForm.teacherName ? '教师标准课时量' : '总标准课时量' }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="stat-item">
            <div class="stat-value">{{ totalConvertedHours }}</div>
            <div class="stat-label">{{ filterForm.teacherName ? '教师折合课时量' : '总折合课时量' }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="stat-item">
            <div class="stat-value">{{ courseCount }}</div>
            <div class="stat-label">课程门数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="stat-item">
            <div class="stat-value">{{ totalStudents }}</div>
            <div class="stat-label">总学生数</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选条件 -->
    <el-card style="margin-bottom: 20px;">
      <template #header>
        <span>筛选条件</span>
      </template>
      <el-form :model="filterForm" label-width="100px" inline>
                         <el-form-item label="教师姓名">
          <el-input 
            v-model="filterForm.teacherName" 
            placeholder="输入教师姓名进行搜索" 
            clearable 
            style="width: 200px;"
            @input="handleSearch"
          />
          <div class="search-tip" v-if="filterForm.teacherName">
            <small>搜索包含"{{ filterForm.teacherName }}"的教师（创建者或授课教师）</small>
          </div>
        </el-form-item>
        <el-form-item label="学年学期">
          <el-select 
            v-model="filterForm.academicYear" 
            placeholder="选择学年学期" 
            clearable 
            style="width: 250px;"
            @change="handleSearch"
          >
            <el-option
              v-for="semester in semesterConfigs"
              :key="semester.academicYear"
              :label="semester.academicYear"
              :value="semester.academicYear"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input 
            v-model="filterForm.courseName" 
            placeholder="输入课程名称关键词" 
            style="width: 200px;"
            @input="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="exportData">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button type="primary" @click="handleSearch" :disabled="!hasSearchConditions">
            搜索
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 搜索状态提示 -->
      <div v-if="filterForm.teacherName || filterForm.academicYear || filterForm.courseName" class="search-status" style="margin-top: 16px;">
        <el-alert
          :title="`当前显示筛选结果：${courseCount} 门课程`"
          :description="getSearchStatusDescription()"
          type="info"
          :closable="false"
          show-icon
        />
      </div>
    </el-card>

    <!-- 课程列表 -->
    <el-card>
      <template #header>
        <span>教学课时列表</span>
      </template>
      <el-table :data="filteredCourseHours" style="width: 100%" v-loading="loading" :empty-text="getEmptyText()">
        <el-table-column prop="creatorName" label="创建教师" width="120" />
        <el-table-column prop="academicYear" label="学年学期" width="200" />
        <el-table-column prop="courseName" label="课程名称" min-width="180" />
        <el-table-column prop="courseNature" label="课程性质" width="120" />
        <el-table-column prop="theoryHours" label="理论学时" width="100" />
        <el-table-column prop="standardClassCount" label="折合标准教学班" width="150" />
        <el-table-column prop="standardHours" label="标准课时量" width="120" />
        <el-table-column prop="conversionFactor" label="折算系数" width="100" />
        <el-table-column prop="convertedHours" label="折合课时量" width="120" />
        <el-table-column prop="teachingClass" label="授课班级" min-width="150" />
        <el-table-column prop="studentCount" label="修读人数" width="100" />
        <el-table-column label="授课教师" min-width="200">
          <template #default="scope">
            <div v-for="member in scope.row.members" :key="member.id" class="member-info">
              <span>{{ member.userName }}</span>
              <el-tag size="small" style="margin-left: 8px;">{{ member.allocatedHours }}课时</el-tag>
              <el-tag size="small" type="info" style="margin-left: 4px;">{{ member.role }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewDetails(scope.row)">查看详情</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="教学课时详情"
      width="1000px"
    >
      <div v-if="selectedCourse" class="course-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学年学期">{{ selectedCourse.academicYear }}</el-descriptions-item>
          <el-descriptions-item label="课程名称">{{ selectedCourse.courseName }}</el-descriptions-item>
          <el-descriptions-item label="课程性质">{{ selectedCourse.courseNature }}</el-descriptions-item>
          <el-descriptions-item label="理论学时">{{ selectedCourse.theoryHours }}</el-descriptions-item>
          <el-descriptions-item label="授课班级">{{ selectedCourse.teachingClass || '无' }}</el-descriptions-item>
          <el-descriptions-item label="修读人数">{{ selectedCourse.studentCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="折合标准教学班">{{ selectedCourse.standardClassCount }}</el-descriptions-item>
          <el-descriptions-item label="标准课时量">{{ selectedCourse.standardHours }}</el-descriptions-item>
          <el-descriptions-item label="折算系数">{{ selectedCourse.conversionFactor }}</el-descriptions-item>
          <el-descriptions-item label="折合课时量">{{ selectedCourse.convertedHours }}</el-descriptions-item>
          <el-descriptions-item label="创建教师">{{ selectedCourse.creatorName }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(selectedCourse.createdAt) }}</el-descriptions-item>
        </el-descriptions>
        
        <div style="margin-top: 20px;">
          <h4>授课教师及分配课时量</h4>
          <el-table :data="selectedCourse.members" style="width: 100%">
            <el-table-column prop="userName" label="教师姓名" width="150" />
            <el-table-column prop="staffNo" label="工号" width="120" />
            <el-table-column prop="department" label="部门" width="150" />
            <el-table-column prop="allocatedHours" label="分配课时量" width="120" />
            <el-table-column prop="role" label="角色" width="120" />
            <el-table-column prop="createdAt" label="添加时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.createdAt) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
 import {
   getAllCourseHours,
   deleteCourseHours,
   getSemesterConfig
 } from '@/api/courseHours'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)
const selectedCourse = ref(null)
 const courseHours = ref([])
 const semesterConfigs = ref([])

 // 筛选表单
 const filterForm = ref({
   teacherName: '',
   academicYear: '',
   courseName: ''
 })

// 计算属性
const filteredCourseHours = computed(() => {
  let filtered = courseHours.value

     if (filterForm.value.teacherName) {
       filtered = filtered.filter(item => {
         const searchName = filterForm.value.teacherName.trim().toLowerCase()
         // 检查创建者姓名
         const creatorMatch = item.creatorName && 
           item.creatorName.toLowerCase().includes(searchName)
         // 检查成员姓名
         const memberMatch = item.members.some(member => 
           member.userName && member.userName.toLowerCase().includes(searchName)
         )
         return creatorMatch || memberMatch
       })
     }

  if (filterForm.value.academicYear) {
    filtered = filtered.filter(item => item.academicYear === filterForm.value.academicYear)
  }

  if (filterForm.value.courseName) {
    filtered = filtered.filter(item => 
      item.courseName.toLowerCase().includes(filterForm.value.courseName.toLowerCase())
    )
  }

  return filtered
})

const totalStandardHours = computed(() => {
  if (filterForm.value.teacherName) {
    // 如果按教师姓名搜索，只统计该教师实际分配的课时量
    const result = filteredCourseHours.value.reduce((total, item) => {
      let itemTotal = 0
      const searchName = filterForm.value.teacherName.trim().toLowerCase()
      
      // 检查成员（授课教师）
      item.members.forEach(member => {
        if (member.userName && member.userName.toLowerCase().includes(searchName)) {
          // 只统计教师实际分配的课时量
          itemTotal += (member.allocatedHours || 0)
          console.log(`课程: ${item.courseName}, 教师: ${member.userName}, 分配课时: ${member.allocatedHours}`)
        }
      })
      
      return total + itemTotal
    }, 0)
    
    console.log(`教师 ${filterForm.value.teacherName} 的总标准课时量: ${result}`)
    return result.toFixed(2)
  } else {
    // 否则统计所有筛选结果的课时量
    return filteredCourseHours.value.reduce((sum, item) => sum + (item.standardHours || 0), 0).toFixed(2)
  }
})

const totalConvertedHours = computed(() => {
  if (filterForm.value.teacherName) {
    // 如果按教师姓名搜索，只统计该教师实际分配的课时量
    const result = filteredCourseHours.value.reduce((total, item) => {
      let itemTotal = 0
      const searchName = filterForm.value.teacherName.trim().toLowerCase()
      
      // 检查成员（授课教师）
      item.members.forEach(member => {
        if (member.userName && member.userName.toLowerCase().includes(searchName)) {
          // 按教师实际分配的课时量计算折合课时量
          const memberRatio = (member.allocatedHours || 0) / (item.standardHours || 1)
          const memberConvertedHours = (item.convertedHours || 0) * memberRatio
          itemTotal += memberConvertedHours
          console.log(`课程: ${item.courseName}, 教师: ${member.userName}, 分配课时: ${member.allocatedHours}, 折合课时: ${memberConvertedHours.toFixed(2)}`)
        }
      })
      
      return total + itemTotal
    }, 0)
    
    console.log(`教师 ${filterForm.value.teacherName} 的总折合课时量: ${result}`)
    return result.toFixed(2)
  } else {
    // 否则统计所有筛选结果的课时量
    return filteredCourseHours.value.reduce((sum, item) => sum + (item.convertedHours || 0), 0).toFixed(2)
  }
})

const courseCount = computed(() => filteredCourseHours.value.length)

// 检查是否有搜索条件
const hasSearchConditions = computed(() => {
  return filterForm.value.teacherName || filterForm.value.academicYear || filterForm.value.courseName
})

const totalStudents = computed(() => {
  return filteredCourseHours.value.reduce((sum, item) => sum + (item.studentCount || 0), 0)
})

// 方法
 const loadData = async () => {
   loading.value = true
   try {
     const [courseHoursData, semesterData] = await Promise.all([
       getAllCourseHours(),
       getSemesterConfig()
     ])
     
     courseHours.value = courseHoursData || []
     semesterConfigs.value = semesterData || []
   } catch (error) {
     console.error('加载数据失败:', error)
     ElMessage.error('加载数据失败')
   } finally {
     loading.value = false
   }
 }

const handleSearch = () => {
  // 搜索逻辑通过计算属性自动处理
}

// 获取搜索状态描述
const getSearchStatusDescription = () => {
  const conditions = []
  
  if (filterForm.value.teacherName) {
    conditions.push(`教师姓名包含"${filterForm.value.teacherName}"`)
  }
  
  if (filterForm.value.academicYear) {
    conditions.push(`学年学期为"${filterForm.value.academicYear}"`)
  }
  
  if (filterForm.value.courseName) {
    conditions.push(`课程名称包含"${filterForm.value.courseName}"`)
  }
  
  return conditions.join('，')
}

// 获取空数据提示文本
const getEmptyText = () => {
  if (loading.value) {
    return '加载中...'
  }
  
  if (hasSearchConditions.value) {
    return '没有找到符合条件的教学课时记录'
  }
  
  return '暂无教学课时数据'
}

 const resetFilter = async () => {
   if (hasSearchConditions.value) {
     try {
       await ElMessageBox.confirm('确定要清除所有搜索条件吗？', '确认重置', {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'warning'
       })
       
       filterForm.value = {
         teacherName: '',
         academicYear: '',
         courseName: ''
       }
       
       ElMessage.success('搜索条件已重置')
     } catch (error) {
       if (error !== 'cancel') {
         console.error('重置失败:', error)
         ElMessage.error('重置失败')
       }
     }
   } else {
     ElMessage.info('当前没有搜索条件')
   }
 }

const viewDetails = (row) => {
  selectedCourse.value = row
  detailDialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个教学课时吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteCourseHours(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败: ' + (error.message || error))
    }
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 生命周期
const exportData = async () => {
  const { exportData: exportUtil } = await import('@/utils/exportUtils')
  
  const filters = {
    semester: filterForm.value.academicYear
  }
  
  await exportUtil('course-hours', filters, '教学课时列表.xlsx')
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.course-hours-overview {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.stat-item {
  text-align: center;
  padding: 16px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.member-info {
  margin-bottom: 4px;
}

.member-info:last-child {
  margin-bottom: 0;
}

.course-detail h4 {
  margin: 0 0 16px 0;
  color: #333;
}

.search-tip {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}

.search-tip small {
  color: #909399;
}

.search-status {
  margin-top: 16px;
}

.search-status .el-alert {
  margin-bottom: 0;
}
</style>
